from datetime import datetime, timedelta, timezone
from fastapi import FastAPI, Request, Response
import uvicorn

# 创建app对象
app = FastAPI()


# 设置cookie
@app.get("/set-cookie")
async def set_cookie(response: Response):
    # 设置1个小时过期
    timeoutdate = datetime.now(timezone.utc) + timedelta(hours=1)
    # timeoutdate = datetime.now(timezone.utc) + timedelta(seconds=10)
    response.set_cookie("mycookie", "hello  tony.", expires=timeoutdate)
    return {"message": "Cookie已经设置"}


# 读取cookie
@app.get("/get-cookie")
async def get_cookie(request: Request):
    mycookie = request.cookies.get("mycookie")

    if mycookie:
        return {"message": f"Cookie是{mycookie}"}
    else:
        return {"message": "Cookie没有发现!"}


if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
